Gatsby 블로그 수식 표현 플러그인 Katex 적용법

2019-11-13

Latex 문법으로 수식 표현을 간단하게 할 수 있는 플러그인으로 Katex, MathJax 두 가지가 있는데,

MathJax는 dependency도 많고 Katex가 렌더링이 체감될 정도로 빠르므로 Katex 플러그인으로 수식표기를 하기로 결정했다.

Katex 플러그인을 Gatsby 블로그에 적용하기 위해서 우선,

$ npm install --save gatsby-remark-katex katex
또는
$ yarn add gatsby-remark-katex katex
을 통해 katex를 설치해준다.

Katex 플러그인을 사용하기 위해 gatsby-transformer-remark 플러그인이 필요한데, 마크다운 설정이 미리 되어있다면 이미 설치되어있을 수 있다.

gatsby-config.js

module.exports = {
  // 
  plugins: [
    
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          
          {
            resolve: `gatsby-remark-katex`,
            options: {
              // Add any KaTeX options from https://github.com/KaTeX/KaTeX/blob/master/docs/options.md here
              strict: `ignore`,
            },
          },
        ],
      },
    },
    
  ],
}

gatsby-transformer-remark 안에 gatsby-remark-katex이 들어가는 꼴로 작성해야 한다.


공식문서

Add Katex CSS to your template: Katex’s CSS file is required to render the formulas correctly. Include the CSS file in your template (example):

require(`katex/dist/katex.min.css`)

katex.min.css를 참조할 수 있도록 조치하라고 되어있는데,

blog post를 띄우는 src/templates/(포스트 관련.js) 파일 안에

나의 경우에는 import '../../../node_modules/katex/dist/katex.min.css';를 추가하여 해결하였다.


이제 Katex가 적용된다.

'$' 문자 하나 사이에 표현하는 inline, 두개 사이에 표현하는 block 방식으로 사용할 수 있다.

$a^2 + b^2 = c^2$ 인라인

a2+b2=c2a^2 + b^2 = c^2 인라인

$$
a^2 + b^2 = c^2  
a^2 + b^2 = c^2  
a^2 + b^2 = c^2  
$$ 블록
a2+b2=c2a2+b2=c2a2+b2=c2a^2 + b^2 = c^2 a^2 + b^2 = c^2 a^2 + b^2 = c^2